<?php
//easyWeChat操作

namespace App\Services\Wx;


use EasyWeChat\MiniApp\Application;


class WxMiniApp
{

    public $app;

    public function __construct()
    {
        //        $config = [
        //            'app_id' => WxConfig::$appId,
        //            'secret' => WxConfig::$secret,
        //
        //            // 下面为可选项
        //            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
        //            'response_type' => 'array',
        //        ];
        //
        //        $this->app = Factory::miniProgram($config);

        $config = [
            'app_id'  => env('APPID'),
            'secret'  => env('APP_SECRET'),
            'token'   => 'easywechat',
            'aes_key' => '......',

            /**
             * 接口请求相关配置，超时时间等，具体可用参数请参考：
             * https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
             */
            'http'    => [
                'throw'   => false, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
                // 'base_uri' => 'https://api.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用，根据不同的模块配置不同的 uri

                'retry' => true, // 使用默认重试配置
                //  'retry' => [
                //      // 仅以下状态码重试
                //      'http_codes' => [429, 500]
                //       // 最大重试次数
                //      'max_retries' => 3,
                //      // 请求间隔 (毫秒)
                //      'delay' => 1000,
                //      // 如果设置，每次重试的等待时间都会增加这个系数
                //      // (例如. 首次:1000ms; 第二次: 3 * 1000ms; etc.)
                //      'multiplier' => 3
                //  ],
            ],
        ];

        $this->app = new Application($config);
    }


    public function getLoginCode()
    {
        return $this->app->app_code->get('login', $optional = [
            'width' => 600,
        ]);
    }

    /**
     * 获取微信小程序用户标识
     * @param $code
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function getUserOpenByCode($code)
    {
        $utils = $this->app->getUtils();
        $res = [];
        try {
            $res = $utils->codeToSession($code);
        } catch (\Exception $e) {
            return resultError('验证失败');
        }
        if (!empty($res['errcode'])) {
            return resultError('登录有误');
        }
        if (empty($res['session_key']) || empty($res['openid'])) {
            return resultError('登录有误');
        }

        $data = [
            'openid'      => $res['openid'],
            'session_key' => $res['session_key'],
        ];

        return resultSuccess($data);
    }

    //    public function pushConsumeNotice($openid, $data = []) {
    //
    //        $templateId = '84U6QieuqURAKiRLgBBFnCr6DCBRtGzM37j_2YLOCSI';
    //        $formId = 21176;
    //
    //        $api = $this->app->getClient();
    //        $res = $api->postJson('cgi-bin/message/wxopen/template/uniform_send', [
    //            'touser' => $openid,
    //            'weapp_template_msg' => [
    //                'template_id' => $templateId,
    //                'page' => '',
    //                'form_id' => $formId,
    //                'data' => [
    //                    'ting1.DATA' => [
    //                        'value' => $data['activity_title'] ?? '',
    //                    ],
    //                    'time2.DATA' => [
    //                        'value' => $data['date_text'] ?? '',
    //                    ],
    //                    'ting3.DATA' => [
    //                        'value' => $data['place_text'] ?? '',
    //                    ],
    //                    'ting4.DATA' => [
    //                        'value' => $data['remark'] ?? '',
    //                    ],
    //                ],
    //            ],
    //        ]);
    //        dd($res->toArray());
    //    }

    /**
     * 过期提醒推送
     * @param $openid
     * @param $data
     * @return \EasyWeChat\Kernel\HttpClient\Response|\Symfony\Contracts\HttpClient\ResponseInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
     */
    public function pushConsumeNotice($openid, $data = [])
    {
        $api = $this->app->getClient();
        $pushParams = [
            'touser'            => $openid,
            'template_id'       => WxConfig::$expireTemplateId,
            'page'              => '/pages/card-list/index',
//            'miniprogram_state' => 'trial', //todo: 爱德 消息跳转体验版，上线需注释
            'data'              => [
                'thing1' => [
                    'value' => $data['activity_title'] ?? '',
                ],
                'time2'  => [
                    'value' => $data['date_text'] ?? '',
                ],
                'thing3' => [
                    'value' => $data['place_text'] ?? '',
                ],
                'thing4' => [
                    'value' => $data['remark'] ?? '',
                ],
            ],
        ];

        return $api->postJson('cgi-bin/message/subscribe/send', $pushParams)->toArray();
    }


}
